<template>
    <div>
        <div>
            <homenav :falg="2"></homenav>
        </div>
        <div class="productContainerafter">
            <div class="productContainer">
                <div class="categoryContainer">
                    <div>
                        <el-button
                            @click="getSubCategory(item,index)"
                            v-for="(item, index) in category"
                            :key="index"
                            size="small"
                            :type="item.color?'success':'primary'"
                        >{{item.categoryName}}</el-button>
                    </div>
                    <div>
                        <el-select
                            v-model="keywods"
                            size="small"
                            filterable
                            clearable
                            remote
                            allow-create
                            reserve-keyword
                            placeholder="请输入关键词"
                            :remote-method="remoteMethod"
                            :loading="loading"
                        >
                            <el-option
                                v-for="(item,indexs) in options"
                                :key="indexs"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                        <el-button id="search" size="small" @click="searchGoods">搜索</el-button>
                    </div>
                </div>
                <div class="subCategoryContainer">
                    <div class="fork">
                        <el-link :type="allBtnType?'primary':''" @click="getAllGoods">全部</el-link>
                        <el-link
                            :type="item.color?'primary':''"
                            @click="gotGoodListBySuncategory(item.id,index)"
                            v-for="(item, index) in subCategory"
                            :key="index"
                        >{{item.subCategoryName}}</el-link>
                    </div>
                    <div class="ordering">
                        <el-link
                            @click="getOrdering(item,index)"
                            v-for="(item,index) in orderingData"
                            :key="index"
                        >{{item.orderingItem}}</el-link>
                    </div>
                </div>
                <div class="goodListContainer">
                    <div class="needbacktotop">
                        <el-card
                            v-for="(item, index) in goodlists"
                            :key="index"
                            shadow="hover"
                            :body-style="{ padding: '0px', width:'220px',brder:'none',height:'300px',margin:'5px'}"
                        >
                            <el-image
                                scroll-container=".appContainer"
                                @click="goodDetails(item)"
                                :src="item.goodCoverImg"
                                lazy
                            ></el-image>
                            <!-- item.goodCoverImg -->
                            <div style="padding: 0px;">
                                <div class="goodname">{{item.goodName}}</div>
                                <div class="goodprice">{{item.goodPrice}}¥</div>
                                <div class="operabtn">
                                    <el-button
                                        @click="goodDetails(item)"
                                        type="text"
                                        class="button"
                                    >更多详细</el-button>
                                </div>
                            </div>
                        </el-card>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import homenav from "../common/homenav.vue";
import $ from "jquery";
export default {
    data() {
        return {
            category: [],
            subCategory: [],
            goodlists: [],
            restaurants: [],
            queryset: [],
            allBtnType: true,
            selectCategoryIndex: null,
            selectSubCategory: null,
            orderingData: [
                { orderingItem: "价格升序", id: 1, orderring: "goodPrice" },
                { orderingItem: "价格降序", id: 2, orderring: "-goodPrice" },
                { orderingItem: "收藏量升序", id: 3, orderring: "goodFavNums" },
                {
                    orderingItem: "收藏量降序",
                    id: 4,
                    orderring: "-goodFavNums"
                },
                { orderingItem: "销量升序", id: 5, orderring: "goodSoldNums" },
                { orderingItem: "销量降序", id: 6, orderring: "-goodSoldNums" },
                { orderingItem: "库存升序", id: 7, orderring: "goodNums" },
                { orderingItem: "库存降序", id: 8, orderring: "-goodNums" }
            ],
            options: [],
            list: [],
            loading: false,
            keywods: null
        };
    },
    methods: {
        // 获取主目录
        getCategory() {
            this.$ajax
                .get("category/")
                .then(res => {
                    //console.log(res.data);
                    this.category = res.data.results;
                    this.category[0].color = true;
                })
                .catch(err => {
                    console.log("err");
                });
        },
        // 获取二级目录并返回第一个二级目录的所有数据
        getSubCategory(item, index) {
            this.selectCategoryIndex = item.id;
            this.selectSubCategory = null;
            this.$ajax
                .get("subcategory/?" + "parentcategory=" + item.id)
                .then(res => {
                    this.subCategory = res.data.results;

                    this.getGoodLists(item.id, true);
                })
                .catch(err => {
                    console.log("err");
                });
            this.category.forEach((items, indexs) => {
                if (indexs == index) {
                    items.color = true;
                } else {
                    items.color = false;
                }
            });
        },
        // 获取产品列表  区分：可以根据子目录获取对应产品，也可以直接通过主目录获取‘全部’产品
        getGoodLists(id, isall, orderStr) {
            this.goodlists = [];
            if (id) {
                if (isall) {
                    this.$ajax
                        .get(
                            "goods/?" +
                                "mainCategory=" +
                                id +
                                "&limit=100" +
                                "&ordering=" +
                                orderStr
                        )
                        .then(res => {
                            this.goodlists = res.data.results;

                            this.getSelectList(this.goodlists);
                        })
                        .catch(err => {
                            console.log(err);
                        });
                } else {
                    this.$ajax
                        .get(
                            "goods/?" +
                                "category=" +
                                id +
                                "&limit=150" +
                                "&ordering=" +
                                orderStr
                        )
                        .then(res => {
                            this.goodlists = res.data.results;
                            this.getSelectList(this.goodlists);
                        })
                        .catch(err => {
                            console.log("err");
                        });
                }
            } else {
            }
        },
        // 点击子目录获取对应产品数据
        gotGoodListBySuncategory(id, index) {
            //this.selectCategoryIndex = null;
            this.selectSubCategory = id;
            this.getGoodLists(id);
            this.allBtnType = false;
            this.subCategory.forEach((item, indexs) => {
                if (index == indexs) {
                    item.color = true;
                } else {
                    item.color = false;
                }
            });
        },
        // 点击‘全部’连接获取全部产品数据
        getAllGoods() {
            this.getGoodLists(this.selectCategoryIndex, true);
            this.allBtnType = true;
            this.subCategory.forEach(item => {
                item.color = false;
            });
        },
        // 进行排序
        getOrdering(item, index) {
            if (this.selectCategoryIndex == null) {
                // 此时用户正在浏览子目录下的产品数据
                this.getGoodLists(
                    this.selectSubCategory,
                    false,
                    item.orderring
                );
            } else if (this.selectSubCategory == null) {
                // 浏览对应主目录下所有数据
                this.getGoodLists(
                    this.selectCategoryIndex,
                    true,
                    item.orderring
                );
            }
            this.getGoodLists();
        },
        // 产品详细
        goodDetails(item) {
            //this.$store.commit("upgoodDetailId",item.id) // 点击的商品id可以传入Vuex里面存储起来，也可以放在路由后面如下：
            this.addGoodClickNums(item);
            this.$router.push({ name: "details", params: { id: item.id } }); // 这里使用路由传参的方式将id传到详细页
        },
        // 递增商品的点击量
        addGoodClickNums(goods) {
            this.$ajax
                .put("goods/" + goods.id + "/", {
                    goodClickNums: goods.goodClickNums + 1
                })
                .then(res => {
                    //console.log(res.data);
                })
                .catch(err => {
                    console.log("addGoodClickNums -- error");
                });
        },
        // 提取搜索框内容
        getSelectList(arrs) {
            this.queryset = [];
            arrs.forEach(item => {
                this.queryset.push(item.goodName);
            });
        },
        remoteMethod(query) {
            if (query !== "") {
                this.loading = true;
                setTimeout(() => {
                    this.loading = false;
                    this.options = this.list.filter(item => {
                        return (
                            item.label
                                .toLowerCase()
                                .indexOf(query.toLowerCase()) > -1
                        );
                    });
                }, 200);
            } else {
                this.options = [];
            }
        },

        // 关键字搜索
        kwSearch(kw) {
            if (kw) {
                this.$ajax
                    .get("goods/?search=" + kw)
                    .then(res => {
                        console.log(res.data.results);
                    })
                    .catch(err => {});
            } else {
                this.$notify({
                    message: "请输入搜索关键字",
                    type: "warning"
                });
            }
        },
        // 搜索按钮
        searchGoods() {
            if (this.keywods !== null && this.keywods !== "") {
                this.$ajax
                    .get("goods/?search=" + this.keywods)
                    .then(res => {
                        if (res.data.results.length > 0) {
                            this.goodlists = res.data.results;
                        } else {
                            this.$notify({
                                message: "没有搜索到相关商品！",
                                type: "warning"
                            });
                        }
                    })
                    .catch(err => {});
            } else {
                this.$notify({
                    message: "请输入搜索内容",
                    type: "warning"
                });
            }
        }
    },
    mounted() {
        this.getCategory();
        let item = { id: 1 };
        this.getSubCategory(item);
        this.getGoodLists(1, true);
    },
    components: {
        homenav
    },
    watch: {
        queryset() {
            if (this.queryset.length > 0) {
                this.list = this.queryset.map(item => {
                    return { value: item, label: item };
                });
            }
        }
    }
};
window.onload = function() {
    document.onkeydown = function(e) {
        if (e.keyCode == 13) {
            $("#search").click();
        }
    };
};
</script>


<style lang="scss" scoped>
.el-input {
    width: 71%;
}
.productContainer {
    width: 100%;
    height: auto;
    min-width: 1236px;
    // border: 1px solid red;
    margin: 0 auto;
    padding-top: 100px;
    // margin-top: 105px;
    .categoryContainer {
        display: flex;
        width: 1233px;
        margin: 2px auto;
        // border: 1px solid red;
        justify-content: flex-start;
        el-button {
            margin: 0 20px;
            font-family: Helvetica, "Hiragino Sans GB", "Microsoft Yahei",
                "微软雅黑", Arial, sans-serif;
        }
        div:nth-child(2) {
            margin-left: 220px;
        }
    }
    .subCategoryContainer {
        min-width: 1195px;
        width: 100%;
        .fork {
            margin-top: 23px;
            display: flex;
            width: 1230px;
            margin: 2px auto;
            // border: 1px solid red;
            justify-content: flex-start;
            // border: 1px solid #aaa;

            // height: 60px;
            padding: 5px 4px;
            .el-link {
                margin-right: 20px;
                font-size: 13px;
                font-family: Helvetica, "Hiragino Sans GB", "Microsoft Yahei",
                    "微软雅黑", Arial, sans-serif;
            }
        }
        .ordering {
            font-family: Helvetica, "Hiragino Sans GB", "Microsoft Yahei",
                "微软雅黑", Arial, sans-serif;
            font-size: 13px;
            // border: 1px solid #ccc;
            padding: 5px 4px;
            width: 1230px;
            margin: 2px auto;
            // border: 1px solid red;
            margin-top: 5px;
            .el-link {
                margin-right: 10px;
            }
        }
    }
    .goodListContainer {
        width: 100%;
        height: auto;
        .needbacktotop {
            overflow: hidden;
            width: 1230px;
            margin: 25px auto;
            // border: 1px solid red;
        }
        .el-card {
            float: left;
            border: none;
            margin: 8px;
            img {
                width: 100%;
            }
            div {
                text-align: center;
                font-family: Helvetica, "Hiragino Sans GB", "Microsoft Yahei",
                    "微软雅黑", Arial, sans-serif;
                .goodname {
                    font-size: 14px;
                    margin-top: 8px;
                }
                .goodprice {
                    font-size: 15px;
                    margin-top: 5px;
                    color: red;
                }
                .operabtn {
                    button {
                        padding: 0;
                    }
                }
            }
        }
    }
}
</style>